#!/bin/bash

# 雷达系统开机自启动安装脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 工作目录
WORK_DIR="/home/admin1/lidar"

# 检查权限
check_permissions() {
    if [ "$EUID" -ne 0 ]; then
        log_error "需要root权限安装系统服务"
        echo "请运行: sudo $0"
        exit 1
    fi
}

# 安装系统服务
install_systemd_service() {
    log_step "安装systemd系统服务..."
    
    # 复制服务文件
    cp "$WORK_DIR/lidar-system.service" /etc/systemd/system/
    
    # 重新加载systemd配置
    systemctl daemon-reload
    
    # 启用服务
    systemctl enable lidar-system.service
    
    log_info "systemd服务安装成功！"
}

# 创建cron任务（备用方案）
install_cron_job() {
    log_step "安装cron定时任务（备用监控）..."
    
    # 创建cron脚本
    cat > /usr/local/bin/lidar-health-check.sh << 'EOF'
#!/bin/bash

# 雷达系统健康检查脚本
WORK_DIR="/home/admin1/lidar"
LOG_FILE="/var/log/lidar-health-check.log"

# 检查端口是否被占用
check_port() {
    local port=$1
    if netstat -tlnp | grep ":$port " > /dev/null 2>&1; then
        return 0  # 端口被占用
    else
        return 1  # 端口空闲
    fi
}

# 记录日志
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" >> "$LOG_FILE"
}

# 检查服务状态
if ! check_port 5000 || ! check_port 7100; then
    log_message "检测到服务异常，尝试重启"
    
    # 切换到工作目录
    cd "$WORK_DIR"
    
    # 重启服务
    sudo -u admin1 ./start_services.sh restart >> "$LOG_FILE" 2>&1
    
    log_message "服务重启完成"
else
    log_message "服务运行正常"
fi
EOF
    
    chmod +x /usr/local/bin/lidar-health-check.sh
    
    # 添加cron任务（每5分钟检查一次）
    (crontab -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/lidar-health-check.sh") | crontab -
    
    log_info "cron健康检查任务安装成功！"
}

# 创建rc.local启动项（兼容性方案）
install_rc_local() {
    log_step "配置rc.local启动项..."
    
    # 备份原有rc.local
    if [ -f /etc/rc.local ]; then
        cp /etc/rc.local /etc/rc.local.backup
    fi
    
    # 创建或更新rc.local
    cat > /etc/rc.local << EOF
#!/bin/bash
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.

# 启动雷达系统服务
sleep 30  # 等待系统完全启动
cd /home/admin1/lidar
sudo -u admin1 ./start_services.sh start >> /var/log/lidar-startup.log 2>&1 &

exit 0
EOF
    
    chmod +x /etc/rc.local
    
    log_info "rc.local启动项配置成功！"
}

# 显示安装结果
show_installation_result() {
    log_step "安装完成！"
    
    echo ""
    echo "=== 自启动配置 ==="
    echo "✅ systemd服务: lidar-system.service"
    echo "✅ cron健康检查: 每5分钟检查一次"
    echo "✅ rc.local启动项: 系统启动时自动运行"
    echo ""
    
    echo "=== 管理命令 ==="
    echo "启动服务: sudo systemctl start lidar-system"
    echo "停止服务: sudo systemctl stop lidar-system"
    echo "查看状态: sudo systemctl status lidar-system"
    echo "查看日志: sudo journalctl -u lidar-system -f"
    echo ""
    
    echo "=== 手动管理 ==="
    echo "启动: cd /home/admin1/lidar && ./start_services.sh start"
    echo "停止: cd /home/admin1/lidar && ./start_services.sh stop"
    echo "状态: cd /home/admin1/lidar && ./start_services.sh status"
    echo ""
    
    echo "=== 日志文件 ==="
    echo "服务日志: /home/admin1/lidar/logs/backend.log"
    echo "监控日志: /home/admin1/lidar/logs/watchdog.log"
    echo "健康检查: /var/log/lidar-health-check.log"
    echo "启动日志: /var/log/lidar-startup.log"
    echo ""
    
    log_info "现在可以安全关闭VSCode，服务将持续运行！"
}

# 主函数
main() {
    log_info "雷达系统开机自启动安装程序"
    
    # 检查权限
    check_permissions
    
    # 安装各种自启动方案
    install_systemd_service
    install_cron_job
    install_rc_local
    
    # 显示结果
    show_installation_result
}

# 执行主函数
main "$@"
